<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="[]"
      :positionName="''"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    > 
     <template #add ><el-button @click="addHeader" v-permission="'gathering/create'" color="#50BC58"  icon="Plus" circle class="ml-4 button"></el-button></template>
    <template #DataImport>
      <el-button color="#081F42" class="ml-[15px]" @click="quickPay"> 快速收款</el-button>
    </template>
     </TopSearch>
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="[]"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
      
    >
      <template #default="{ row, propname }">
        <div  v-if="propname === 'paytype'">
          <el-tag type="success" >{{row[propname].name}}</el-tag>
          </div>
      </template>

        <template #search_operate>
            <el-table-column  fixed="right" min-width="260px" label="操作">
              <template #default="scope">
               <div class="flex ">
                <el-link   type="primary" :underline="false" v-if="scope.row.debt !== '0.00'"  @click="collection(scope.row,scope.$index, )" >收款</el-link >
                <el-link v-permission="'gathering/print'"  type="primary" :underline="false"  @click="print(scope.row,scope.$index, )" >列印</el-link >
                <el-link v-permission="'gathering/delete'"  type="primary" :underline="false"  @click="abandonment(scope.row,scope.$index, )" >作廢</el-link >
               </div>
              </template>
            </el-table-column>
        </template>
    </ProTable>
    <addEdit :echo="echo" ref="AddEditref" @update="addTableList"></addEdit>
  </div>
</template>

<script setup>
import { reactive, ref,onMounted,computed, watch, nextTick } from "vue"
import { elProps,controlWidth } from "./index.js"
import { setFormConfig } from "./formConfig";
import addEdit from './addEdit/index.vue'
 import {proceeds,delProceeds} from '@/http/index.js'
 import {messageBox,message,loading,closeLoading} from '@/common/function.js'
import { add,} from 'high-precision-four-fundamental-rules'
import {useRoute,useRouter } from "vue-router";

 const echo = ref({})
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  paytype:'收款方式',
  student_name: "學生名稱",
  invoice_id: "發票編號",
  number:'收款編號',
  consult:'參考編號',
  create_time:'收款日期',
  username:'員工',
  totalmoney:'累計已付',
  debt:'現時尚欠',
  remark:'備註',
  notice:'須知',
};
// 表格顶部操作按钮
const control = ["search", "dels"];

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const searchHeader = (e) => {
    Object.assign(obj, e);
      tableList();
};
const AddEditref = ref(null);
const addHeader = async() => {
    echo.value={
    id:'',
    student_name:'',
    invoice_id:'',
    student_id:'',
    money:'',
    payment:'',
    remark:'',
    notice:'',
    debt:'',
    course: [], //課程
    product: [], //產品
    products_group: [], //產品組合
    ticket:[]//
  }
  delete echo.value.id
  AddEditref.value.paymentData()
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = 'add'
  AddEditref.value.isHide = true//發票
  AddEditref.value.isFlash = true//發票詳情
};
const quickPay = ()=>{
      echo.value={
    course: [], //課程
    product: [], //產品
    products_group: [], //產品組合
    ticket:[]//
  }
  AddEditref.value.paymentData()
  AddEditref.value.buttonType = 'quick'
  AddEditref.value.dialogValue = true
  AddEditref.value.isHide = false//發票
  AddEditref.value.isFlash = false//發票詳情
}
const router = useRouter()
const print = (row)=>{
            let {
          href
        } = router.resolve({
          path: '/gatheringPrint',
          query: {
           data:JSON.stringify(row),
          }
        })
        window.open(href, '', 'height=700,width=800,top=300,left=800')
}
const collection =(row)=>{
  console.log(row);
  AddEditref.value.paymentData()
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = 'edit'
  AddEditref.value.isHide = false//發票
  AddEditref.value.isFlash = true//發票詳情
   const {id,create_time,username,school_id,student_name,invoice_id,student_id,payment,remark,notice,debt,course,product,products_group,ticket} = row
   echo.value = {id,create_time,username,school_id,student_name,invoice_id,student_id,payment,remark,notice,debt,course,product,products_group,ticket}
   echo.value.money = 0
   if (echo.value.course && echo.value.course.length>0) {
    echo.value.course.map(e => {
      e.actual = e.debt, e.debts = 0
echo.value.money =  add(parseFloat(e.debt), echo.value.money, 2)
      })
   }
      if (echo.value.product && echo.value.product.length>0) {
    echo.value.product.map(e=>{
      e.actual = e.debt,e.debts = 0
      echo.value.money =  add(parseFloat(e.debt), echo.value.money, 2)
      })
   }
      if (echo.value.products_group && echo.value.products_group.length>0) {
    echo.value.products_group.map(e=>{
      e.actual = e.debt,e.debts = 0
      echo.value.money =  add(parseFloat(e.debt), echo.value.money, 2)
      })
   }
      if (echo.value.ticket && echo.value.ticket.length>0) {
    echo.value.ticket.map(e=>{
      e.actual = e.debt,e.debts = 0
      echo.value.money =  add(parseFloat(e.debt), echo.value.money, 2)
      })
   }
}
const abandonment = (row)=>{
  messageBox().then(()=>{
    delTableList(row.id)
  })
}

const delTableList = async(id)=>{
        const data = await delProceeds(id) 
          if (data.code  == 200) {
              tableList()
              message('已成功刪除該收款')
          }else{
              message('刪除收款數據失敗')
          }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
    let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = () => {
  messageBox().then(()=>{
    delTableList(ids.value)
  })
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};


const obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableData = ref([])
const tableList = async ()=>{
  loading()
  const data = await proceeds(obj)
  console.log(data);
  if (data.code == 200) {
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    tableData.value = data.data.data
  }
  closeLoading()
}
const addTableList = async()=>{
  await tableList()
}
const pageRefresh = async()=>{
  await tableList()
}
import { userouteStore } from "@/stores/index.js";
import { storeToRefs } from "pinia";
const store = userouteStore();
const route = useRoute();

const routeRenew = ()=>{
  console.log(typeof(route.query.showInfo));
// const {showInfo} = store
let {data} = store
  if (JSON.stringify(data) !=="{}") {
  data = JSON.parse(data)
}
console.log(data);
    if (route.query.showInfo == 'true') {
  AddEditref.value.paymentData()
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = 'add'
  AddEditref.value.isHide = false//發票
  AddEditref.value.isFlash = true//發票詳情
   const {id,student_name,student_id,course,product,products_group,ticket,number,debt} = data
   echo.value = {id,student_name,student_id,course,product,products_group,ticket,number,debt}
   echo.value.invoice_id = id
  delete echo.value.id
echo.value.money = 0
   if (echo.value.course && echo.value.course.length>0) {
    echo.value.course.map(e => {
      e.number = echo.value.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt = e.total_prices,e.debts = e.total_prices
      echo.value.money =  add(parseFloat(e.total_prices), echo.value.money, 2)
      })
   }
         if (echo.value.product && echo.value.product.length>0) {
    echo.value.product.map(e=>{
 e.number = echo.value.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt = e.total_prices,e.debts = e.total_prices
      echo.value.money =  add(parseFloat(e.total_prices), echo.value.money, 2)
      })
   }
      if (echo.value.products_group && echo.value.products_group.length>0) {
    echo.value.products_group.map(e=>{
 e.number = echo.value.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt = e.total_prices,e.debts = e.total_prices
      echo.value.money =  add(parseFloat(e.total_prices), echo.value.money, 2)
      })
   }
      if (echo.value.ticket && echo.value.ticket.length>0) {
    echo.value.ticket.map(e=>{
 e.number = echo.value.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt = e.total_prices,e.debts = e.total_prices
      echo.value.money =  add(parseFloat(e.total_prices), echo.value.money, 2)
      })
   }
   console.log(echo.value);
    }
}
onMounted(() => {
  tableList()
  routeRenew()
})
</script>

<style lang="less" scoped>

.box {
  padding: 16px 33px;
  :deep(.warning-row){
  --el-table-tr-bg-color: #fdc3c3 !important;
  }
}
.button{
  color: #fff;
}
.flex{
  .el-link{
    margin-right: 40px;
  }
}
</style>